package net.oschina.app.ui;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebView;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import net.oschina.app.R;
import net.oschina.app.bean.News;
import net.oschina.app.bean.NewsDetail;
import net.oschina.app.util.StringUtils;
import net.oschina.app.util.UIHelper;
import net.oschina.app.util.XmlUtils;

import java.io.IOException;
import java.io.InputStream;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by Ethan on 2017/4/2.
 */

public class NewsItemDetailActivity extends AppCompatActivity {
    @BindView(R.id.tb_news)
    Toolbar mTbNews;
    @BindView(R.id.tv_news_content)
    WebView mTvNewsContent;
    @BindView(R.id.ib_typing_hide)
    ImageButton mIbTypingHide;
    @BindView(R.id.et_input)
    EditText mEtInput;
    @BindView(R.id.ib_emoji)
    ImageButton mIbEmoji;
    @BindView(R.id.ib_biz_chat)
    ImageButton mIbBizChat;
    @BindView(R.id.ib_typing_show)
    ImageButton mIbTypingShow;
    @BindView(R.id.ib_edit)
    ImageButton mIbEdit;
    @BindView(R.id.ib_collect)
    ImageButton mIbCollect;
    @BindView(R.id.ib_share)
    ImageButton mIbShare;
    @BindView(R.id.ib_report)
    ImageButton mIbReport;
    @BindView(R.id.ll_input)
    LinearLayout mLlInput;
    @BindView(R.id.ll_state_select)
    LinearLayout mLlStateSelect;
    @BindView(R.id.ib_show)
    ImageButton mIbShow;
    @BindView(R.id.tv_comment_num)
    TextView mTvCommentNum;
    @BindView(R.id.ib_comment)
    FrameLayout mIbComment;
    private int mId;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_news_item_detail);
        ButterKnife.bind(this);

        //获取到点击资讯页面等条目跳转到详情页面时传输的id数据
        mId = getIntent().getIntExtra("id", 0);

        //设置Toolbar显示
        setSupportActionBar(mTbNews);

        //设置Toolbar显示导航键(返回键)
        getSupportActionBar().setHomeButtonEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        //点击事件
        initEvent();

        //加载详情页面数据
        loadData();
    }

    private void initEvent() {
        //设置Toolbar点击导航键返回,并销毁当前页面
        mTbNews.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        mTbNews.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                Toast.makeText(NewsItemDetailActivity.this, "刷新", Toast.LENGTH_SHORT).show();
                return true;
            }
        });

        //设置点击事件
        mIbTypingShow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mLlStateSelect.setVisibility(View.GONE);
                mLlInput.setVisibility(View.VISIBLE);
            }
        });
        mIbTypingHide.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mLlStateSelect.setVisibility(View.VISIBLE);
                mLlInput.setVisibility(View.GONE);
            }
        });
        mIbEdit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mLlStateSelect.setVisibility(View.GONE);
                mLlInput.setVisibility(View.VISIBLE);
            }
        });
        mIbComment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(NewsItemDetailActivity.this, CommentDetailActivity.class);
                startActivity(intent);
            }
        });
        mIbShow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(NewsItemDetailActivity.this, CommentDetailActivity.class);
                startActivity(intent);
            }
        });
        mIbCollect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(NewsItemDetailActivity.this, LoginActivity.class);
                startActivity(intent);
            }
        });
    }

    private void loadData() {
        //根据获取的id数据拼接url
        String url = "http://10.0.2.2:8080/oschina/detail/news_detail/" + mId + ".xml";

        //创建client对象
        OkHttpClient client = new OkHttpClient();

        //根据url构建请求
        Request request = new Request.Builder().url(url).build();

        //根据请求获得Call对象
        Call call = client.newCall(request);

        //根据call对象异步获取网络数据
        call.enqueue(new Callback() {
            //获取数据失败执行的方法
            @Override
            public void onFailure(Call call, IOException e) {

            }

            //获取数据成功响应的方法
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //根据响应获取响应流
                InputStream inputStream = response.body().byteStream();

                //通过XML解析工具,传入对应的Bean类字节码文件对象,把响应流中的数据解析成对应的实体Bean
                final NewsDetail newsDetail = XmlUtils.toBean(NewsDetail.class, inputStream);

                //通过解析出来的实体Bean获取展示界面需要的信息,然后将信息展示在界面(注意:此为UI更改操作,需确保在UI线程中执行)
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        String webViewBody = getWebViewBody(newsDetail.getNews());
                        mTvNewsContent.loadDataWithBaseURL("", webViewBody,
                                "text/html", "UTF-8", "");
                    }
                });
            }
        });
    }

    //动态添加,替换内容
    protected String getWebViewBody(News mDetail) {
        StringBuffer body = new StringBuffer();
        body
                .append(UIHelper.WEB_STYLE)
                .append(UIHelper.WEB_LOAD_IMAGES);
        // 添加title
        body.append(String.format("<div class='title'>%s</div>", mDetail.getTitle()));
        // 添加作者和时间
        String time = StringUtils.friendly_time(mDetail.getPubDate());
        String author = String.format("<a class='author' href='http://my.oschina.net/u/%s'>%s</a>", mDetail.getAuthorId(), mDetail.getAuthor());
        body.append(String.format("<div class='authortime'>%s&nbsp;&nbsp;&nbsp;&nbsp;%s</div>", author, time));
        // 添加图片点击放大支持
        body.append(setHtmlCotentSupportImagePreview(mDetail.getBody()));


        // 更多关于***软件的信息
        String softwareName = mDetail.getSoftwareName();
        String softwareLink = mDetail.getSoftwareLink();
        if (!StringUtils.isEmpty(softwareName)
                && !StringUtils.isEmpty(softwareLink))
            body.append(String
                    .format("<div class='oschina_software' style='margin-top:8px;font-weight:bold'>更多关于:&nbsp;<a href='%s'>%s</a>&nbsp;的详细信息</div>",
                            softwareLink, softwareName));

        // 相关新闻
        if (mDetail != null && mDetail.getRelatives() != null
                && mDetail.getRelatives().size() > 0) {
            String strRelative = "";
            for (News.Relative relative : mDetail.getRelatives()) {
                strRelative += String.format(
                        "<li><a href='%s' style='text-decoration:none'>%s</a></li>",
                        relative.url, relative.title);
            }
            body.append("<p/><div style=\"height:1px;width:100%;background:#DADADA;margin-bottom:10px;\"/>"
                    + String.format("<br/> <b>相关资讯</b><ul class='about'>%s</ul>",
                    strRelative));
        }
        body.append("<br/>");
        // 封尾
        body.append("</div></body>");
        return body.toString();
    }

    //所有图片设置点击事件,调用java本地代码
    public static String setHtmlCotentSupportImagePreview(String body) {
        // 读取用户设置：是否加载文章图片--默认有wifi下始终加载图片
        if (true) {
            // 过滤掉 img标签的width,height属性
            body = body.replaceAll("(<img[^>]*?)\\s+width\\s*=\\s*\\S+", "$1");
            body = body.replaceAll("(<img[^>]*?)\\s+height\\s*=\\s*\\S+", "$1");
            // 添加点击图片放大支持
            // 添加点击图片放大支持
            body = body.replaceAll("(<img[^>]+src=\")(\\S+)\"",
                    "$1$2\" onClick=\"javascript:mWebViewImageListener.showImagePreview('$2')\"");
        } else {
            // 过滤掉 img标签
            body = body.replaceAll("<\\s*img\\s+([^>]*)\\s*>", "");
        }
        return body;
    }

    //创建显示菜单按钮
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        //更改菜单按钮的图片
        getMenuInflater().inflate(R.menu.refresh_menu, menu);
        return true;
    }
}
